/**
 * ...
 * @author HTML5
 */
 
 
MouseTracker.MOUSE_UP = "mouseUp";
MouseTracker.MOUSE_DOWN = "mouseDown";
MouseTracker.DOUBLE_CLICK = "doubleClick";
 
function MouseTracker( p_element ) 
{
	
	var m_element = p_element || document;
	var _public = this;
	var _lastTime = 0;
	
	this.down = false;
	this.lastX = 0;
	this.lastY = 0;
	this.mouseX = 0;
	this.mouseY = 0;
	this.localX = 0;
	this.localY = 0;
	this.skip  = 0;
	this.signal = new Signal();
	
	function touchHandler(event)
	{
		
		var l_time = new Date().getTime();
		var l_touches = event.changedTouches;
		
		if( event.type == "touchstart" )
		{
			event.preventDefault();
			
			if( l_time - _lastTime < 500 )
			{
				_public.signal.dispatchEvent( MouseTracker.DOUBLE_CLICK );
			}
			
			
			_public.down = true;
			_public.lastX = l_touches[0].pageX;
			_public.lastY = l_touches[0].pageY;
			_public.signal.dispatchEvent( MouseTracker.MOUSE_DOWN );
			
			_lastTime = l_time;
		}
		else if( event.type == "touchend" )
		{
			_public.down = false;
			_public.lastX = l_touches[0].pageX;
			_public.lastY = l_touches[0].pageY;
			_public.signal.dispatchEvent( MouseTracker.MOUSE_UP );
		}
		else
		{
			event.preventDefault();
			this.skip = ( this.skip + 1 ) % 4;			
			
			if( this.skip < 3 )
				return;
		}
		
		_public.mouseX = l_touches[0].pageX;
		_public.mouseY = l_touches[0].pageY;
	}
	
	function mouseHandler(event)
	{
	
		var l_time = new Date().getTime();
		var l_touches = event.changedTouches;
		
		if( event.type == "mousedown" )
		{
			event.preventDefault();
			
			if( l_time - _lastTime < 500 )
			{
				_public.signal.dispatchEvent( MouseTracker.DOUBLE_CLICK );
			}
			
			_public.down = true;
			_public.lastX = event.pageX;
			_public.lastY = event.pageY;
			_public.signal.dispatchEvent( MouseTracker.MOUSE_DOWN );
			
			_lastTime = l_time;
		}
		else if( event.type == "mouseup" )
		{
			_public.down = false;
			_public.lastX = event.pageX;
			_public.lastY = event.pageY;
			_public.signal.dispatchEvent( MouseTracker.MOUSE_UP );
		}
		else
		{
			this.skip = ( this.skip + 1 ) % 5;
			
			if( this.skip < 4 )
				return;
		}
		
		_public.mouseX = event.pageX;
		_public.mouseY = event.pageY;
		_public.localX = event.layerX;
		_public.localY = event.layerY;
	}
	

	m_element.addEventListener( "touchmove", 	 touchHandler );
	m_element.addEventListener( "touchstart", 	 touchHandler );
	m_element.addEventListener( "touchend", 	 touchHandler );
	
	m_element.addEventListener("mousemove", 	mouseHandler );
	m_element.addEventListener("mouseup", 		mouseHandler );
	m_element.addEventListener("mousedown", 	mouseHandler );
	

	
}